/*
 * Copyright © 2011 Nokia Corporation. All rights reserved.
 * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
 * Oracle and Java are trademarks or registered trademarks of Oracle and/or its
 * affiliates. Other product and company names mentioned herein may be trademarks
 * or trade names of their respective owners. 
 * See LICENSE.TXT for license information.
 */

package com.nokia.example.battletank.game;

import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.TiledLayer;

public class Hud {
    public static final int NONE = 0;
    public static final int CONTINUE = 1;
    public static final int NEWGAME = 2;

    private final Resources resources;
    private int width = 0;
    private TiledLayer background;

    public volatile int lives;
    public volatile int score;
    public volatile int enemies;
    public volatile int leftButton = NONE;

    private final int padding;
    
    public Hud(Resources r, int w, int h) {
        resources = r;
        padding = r.gridSizeInPixels/2;
    }

    private void updateBackground(int w, int h) {
        if(background == null || w != width) {
            width = w;
            Image bg = resources.hudBackground;
            background = new TiledLayer(1, (w-1)/bg.getWidth() + 1, bg, bg.getWidth(), bg.getHeight());
            background.fillCells(0, 0, background.getColumns(), 1, 1);
        }
    }

    public void paint(Graphics g, int w, int h) {
        updateBackground(w, h);

        background.setPosition(0, 0);
        background.paint(g);
        // TODO to improve performance use images not strings
        g.setFont(Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL));
        int textOffset = (background.getHeight() - g.getFont().getHeight())/2;
        g.setColor(0x00ffffff);
        g.drawImage(resources.lifeIcon, padding, 0, Graphics.LEFT | Graphics.TOP);
        int x = padding + resources.lifeIcon.getWidth();
        g.drawString(" x "+lives, x, textOffset, Graphics.LEFT | Graphics.TOP);
        g.drawString("SCORE "+score, w/2, textOffset, Graphics.HCENTER | Graphics.TOP);
        g.drawString(" x "+enemies, w - padding, textOffset, Graphics.RIGHT | Graphics.TOP);
        x = w - g.getFont().stringWidth(" x "+enemies) - padding;
        g.drawImage(resources.enemyIcon, x, 0, Graphics.RIGHT | Graphics.TOP);
        
        background.setPosition(0, h - background.getHeight());
        background.paint(g);
        int y = h - textOffset;
        g.drawString("MENU", w - padding, y, Graphics.RIGHT | Graphics.BOTTOM);
        if(leftButton == CONTINUE) g.drawString("CONTINUE", padding, y, Graphics.LEFT | Graphics.BOTTOM);
        else if(leftButton == NEWGAME) g.drawString("NEW GAME", padding, y, Graphics.LEFT | Graphics.BOTTOM);
    }
}
